package com.zang.blogz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zang.blogz.constant.ResultConstant;
import com.zang.blogz.entity.Role;
import com.zang.blogz.entity.RoleMenu;
import com.zang.blogz.entity.RoleResource;
import com.zang.blogz.mapper.RoleMapper;
import com.zang.blogz.result.Result;
import com.zang.blogz.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.github.vampireachao.stream.core.optional.Opp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 朵橙i
 * @since 2022-06-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleResourceService roleResourceService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    @Transactional
    public List<RoleResource> updateResource(Integer roleId, List<Integer> resourceIds) {

        if (CollectionUtil.isEmpty(resourceIds)) {

            roleResourceService.deleteResources(roleId);
            return Collections.singletonList(new RoleResource(null, roleId, null));
        }

        roleResourceService.deleteResources(roleId);

        userInfoService.deleteSecurityCache();

        return roleResourceService.addRoleResource(roleId, resourceIds);
    }

    @Override
    @Transactional
    public List<RoleMenu> updateMenu(Integer roleId, List<Integer> menuIds) {

        if (Opp.ofColl(menuIds).isEmpty()){

            roleMenuService.deleteMenu(roleId);

            return Collections.singletonList(new RoleMenu(null, roleId, null));
        }

        roleMenuService.deleteMenu(roleId);

        userInfoService.deleteSecurityCache();

        return roleMenuService.addRoleMenu(roleId, menuIds);
    }

    @Override
    public Result<Role> saveOrUpdateRole(Role role) {

        if (Opp.of(role.getId()).isEmpty()){

            save(role);
            return Result.ok(ResultConstant.SAVE_SUCCESS,role);
        }

        updateById(role);

        return Result.ok(ResultConstant.UPDATE_SUCCESS,role);

    }

    @Override
    public Result<Boolean> deleteRole(Integer roleId) {

        if (userRoleService.isCanDelete(roleId)){

            removeById(roleId);
            return Result.ok(ResultConstant.DELETE_SUCCESS);
        }

        throw new RuntimeException("还有用户为当前角色无法删除");

    }
}
